const express = require('express')
const xlsx = require('xlsx')
const jwt = require('jsonwebtoken')
const { sendResponse } = require('../utils/sendResponse.js')
const { getFilePath } = require('../utils/constants.js') // 引入常量
const router = express.Router()
// 使用绝对路径
const filePath = getFilePath('users')
const secretKey = 'your-secret-key'

// 登录路由
router.post('/login', (req, res) => {
  const { account, password } = req.body

  if (!account || !password) {
    return sendResponse(res, 400, {}, '请提供账号和密码。')
  }

  const workbook = xlsx.readFile(filePath)
  const worksheet = workbook.Sheets['users']
  const usersData = xlsx.utils.sheet_to_json(worksheet)
  const user = usersData.find((user) => user.Account === account)

  if (!user) {
    return sendResponse(res, 400, {}, '账号未注册。')
  }

  if (user.Password !== password) {
    return sendResponse(res, 400, {}, '密码错误。')
  }

  const token = jwt.sign({ userId: user.ID, account: user.Account, username: user.Username }, secretKey, { expiresIn: '3h' })

  return sendResponse(res, 200, { token, user }, '登录成功！')
})

module.exports = router
